﻿using System;
using System.IO;

class SerializeUtilities
{
    static void Main()
    {
        //string picture = @"c:\DOWNLOADS\GRE.jpg";
        string notepad = @"C:\Windows\system32\notepad.exe";
        EncodeAndDecodeFile(notepad);
    }
    //Method doesn't provide adding new lines every 40 symbols but in 76
    private static void EncodeAndDecodeFile(string path)
    {
        {
            string encodedData = GetBase64String(path);
            Console.WriteLine(encodedData);
            string fileName = path.Substring(path.LastIndexOf('\\') + 1);

            WriteToTextFile(encodedData, fileName);
            string encodedFromFile = ReadFromTextFile(fileName);

            WriteBackToOriginalFile(encodedFromFile, fileName);
        }
    }

    private static void WriteBackToOriginalFile(string encodedFromFile, string fileName)
    {
        byte[] array = Convert.FromBase64String(encodedFromFile);
        using (FileStream writer = new FileStream(
            fileName, FileMode.Create, FileAccess.Write))
        {
            writer.Write(array, 0, array.Length);
        }
    }

    private static string ReadFromTextFile(string fileName)
    {
        string result;
        using (var reader = new StreamReader(fileName + ".txt"))
        {
            result = reader.ReadToEnd();
        }
        return result;
    }

    private static void WriteToTextFile(string encodedData, string fileName)
    {
        using (var writer = new StreamWriter(fileName + ".txt"))
        {
            writer.Write(encodedData);
        }
    }

    private static string GetBase64String(string path)
    {
        string encodedData;
        using (FileStream reader = new FileStream(path,FileMode.Open, FileAccess.Read))
        {
            byte[] filebytes = new byte[reader.Length];
            reader.Read(filebytes, 0, Convert.ToInt32(reader.Length));

            encodedData = Convert.ToBase64String(filebytes, Base64FormattingOptions.InsertLineBreaks);
        }
        return encodedData;
    }
}

